#include <iostream>
#include <ctype.h>
#include <string>
#include <unordered_map>
#include <utility>
#include <fstream>
#include <sstream>

using std::cout;
using std::endl;
using std::cerr;
using std::string;
using std::unordered_map;
using std::ifstream;
using std::ofstream;
using std::istringstream;


class Dictionary
{
public:
    void read(const string &filename){
        ifstream ifs(filename);
        if(!ifs){
            cerr<<"ifs is not good"<<endl;
            return;
        }
        
        string line;
        while(getline(ifs,line)){
            istringstream iss(line);
            string word;
            while(iss >> word){
                //如果单词不合法，比如abc123 abc?? 这种字符串
                string real_word = dealword(word);
                //如果是合法单词，存入vector
                insert(real_word);
            }
        }

        ifs.close();
    }

    string dealword(const string &word){   
        //&dealword，防止string类型返回时的拷贝构造，但可能返回临时对象，所以去掉&
        //const 防止右值问题
        //&word 防止形参实参结合的拷贝构造
        for(size_t idx=0;idx!=word.size();++idx){
            // if(word[idx]>='a' && word[idx]<="z");
            // if(word[idx]>='A' && word[idx]<="Z");
            if(!isalpha(word[idx]))  //返回0，代表不是字母
                return string();
        }
        return word;
    }

    //把结果写到另外一个文件里
    void store(const string &filename){
        ofstream ofs(filename);
        if(!ofs){
            cout<<"ofstream is not good"<<endl;
            return;
        }

        for(auto it=_dict.begin(); it!= _dict.end(); ++it){
            ofs<<it->first<<"        "<<it->second<<endl;
        }

        ofs.close();
    }

    void insert(const string &word){
        if(word==string())
            return;
        
        if(_dict.count(word)){
            ++_dict[word];
        }
        else
            _dict[word]=1;
    }

private:
    unordered_map<string,int> _dict;
};

void test(){
   Dictionary dict;
   dict.read("The_Holy_Bible.txt");
   dict.store("result_unmap.txt");
}

int main()
{   
    test();
    return 0;
}

